<template>
  <div class="search-suggestion">
    <van-cell icon="search" v-for="(text, index) in suggestions" :key="index">
      <div
        slot="title"
        v-html="highlight(text)"
        @click="$emit('search', text)"
      ></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestions: [],
      str: ''
    }
  },
  computed: {},
  watch: {
    searchText: {
      handler: debounce(function(val) {
        this.loadSearchSuggestions(val)
      }, 800),
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 定义获取数据方法
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('数据获取失败，请稍后重试')
      }
    },
    // 高亮方法
    highlight(text) {
      const highlightStr = `<span style="color:red;">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highlightStr)
    }
  }
}
</script>

<style scoped lang="less"></style>
